package me.numark.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.Toast;

import com.sina.weibo.sdk.api.BaseMediaObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.utils.Utility;

/**
 * Created by kHRYSTAL on 2015/8/27.
 */
public class SinaShareManager{


    private static String sinaAppKey;

    private IWeiboShareAPI sinaAPI;

    public void registSina(Context context){

        if(sinaAppKey == null){
            sinaAppKey = Constants.SinaAppKey;
        }
        if(sinaAppKey != null){
            initSinaShare(context);
        }
    }


    public void shareWebPage(ShareContentWebpage shareContent, Context context){
        WeiboMessage weiboMessage = new WeiboMessage();
        weiboMessage.mediaObject = getWebpageObj(shareContent);
        SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
        request.transaction = buildTransaction("sinatext");
        //Log.d("Transation",request.transaction);
        request.message = weiboMessage;
        sinaAPI.sendRequest((Activity) context,request);
    }

    private BaseMediaObject getTextObj(String text) {
        TextObject textObject = new TextObject();
        textObject.text = text;
        return textObject;
    }

    private WebpageObject getWebpageObj(ShareContentWebpage shareContent){
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = shareContent.getTitle();
        mediaObject.description = shareContent.getContent();

        Bitmap bmp = shareContent.getBitmap();
        mediaObject.setThumbImage(bmp);
        mediaObject.actionUrl = shareContent.getURL();
        mediaObject.defaultText = shareContent.getContent();
        return mediaObject;
    }

    private void initSinaShare(Context context){
        sinaAPI = WeiboShareSDK.createWeiboAPI(context, sinaAppKey);
        if (!checkSinaInstalled()) {
            Toast.makeText(context, "未安装微博", Toast.LENGTH_SHORT).show();
            return;
        }
        sinaAPI.registerApp();
    }

    private boolean checkSinaInstalled() {
        boolean isInstalledWeibo = sinaAPI.isWeiboAppInstalled();
        return isInstalledWeibo;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
}
